﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Resources;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using NewsPortal.Models;
using NewsPortal.Linq;
using NewsPortal.DataContracts;
using System.Data.Linq;
using Storage;

namespace NewsPortal.Controllers
{
    public class EditorController : Controller
    {
        public const string ERROR_NOT_LOGGED_IN = "NotLoggedIn";
        public const string ERROR_WRONG_LOGIN_PASS = "WrongLoginPass";
        public const string ERROR_SESSION_TIMEOUT = "SessionTimeout";
        public const string ERROR_NOPICTURE = "NoPicture" ;

        //
        // GET: /Editor/

        public ActionResult Index()
        {
            return RedirectToAction("Run");            
        }

        [HttpPost]
        public ActionResult Add(FormCollection form,HttpPostedFileBase file)
        {
            if (file == null)
            {
                TempData["error"] = ERROR_NOPICTURE;
                return RedirectToAction("Run");
            }

            // Сохраняем картинку
            var imageConnection = new Storage.MongoDbStorageProxy();
            var newImage = new Entity(System.Guid.NewGuid());
             
            byte[] buffer = new byte[file.ContentLength];
            int read = file.InputStream.Read(buffer, 0, buffer.Length);
            
            newImage.Thumbnail = buffer;
            newImage.Body = buffer;     
            imageConnection.Save(newImage);

            // Сохраняем саму новость
            var connection = DataContextFactory.Create();
            Table<News> table = connection.GetTable<News>();
            News news = new News();
            news.Body = form["body"];
            news.ShortText = form["shortText"];
            news.CategoryId = new Guid(form["category"]);
            news.Id = Guid.NewGuid();
            news.Moment = DateTime.Now;
            news.PictureId = newImage.Id;
            news.Title = form["title"];

            table.InsertOnSubmit(news);
            connection.SubmitChanges();

            TempData["ok"] = "newsok";
            return RedirectToAction("Run");
        }

        [HttpPost]
        public ActionResult DoLogin(string login,string pass)
        {
            var connection = DataContextFactory.Create();
            var resId =
                connection.GetTable<Users>().Any(x => x.Login == login && x.Password == Utils.Ciphering.CipheringUtils.getMd5Hash(pass + "&@S#0A"));                       
            if (resId)
            {
                var timeout = Double.Parse(ConfigurationManager.AppSettings["EditorSessionTimeoutMinutes"]);
                var cookieLive = DateTime.Now.AddMinutes(timeout);
                Response.Cookies.Add(new HttpCookie("sid", Utils.Ciphering.CipheringUtils.EncryptString(cookieLive.ToString())));
            }
            else
            {
                TempData["error"] = ERROR_WRONG_LOGIN_PASS;
                return RedirectToAction("Login");
            }
            return RedirectToAction("Run");            
        }

        public ActionResult Login()
        {
            ViewData["ErrorMessage"] = System.Web.HttpContext.GetGlobalResourceObject("ErrorMessages", (String)TempData["error"]);
            //Utils.Resources.ResourcesUtil.ReadErrorResourceValue(error);
            return View("EditorLoginView");
        }

        public ActionResult Run()
        {
            var cookie = Request.Cookies.Get("sid");
            // Если куки нет, просим залогинится
            if (cookie == null)
            {
                TempData["error"] = ERROR_NOT_LOGGED_IN;
                return RedirectToAction("Login");
            }
            DateTime cookieTime;
            // Если время вышло, или же мы рестартили сервер (поменялся ключ) просим опять залогинится
            var res = DateTime.TryParse(Utils.Ciphering.CipheringUtils.DecryptString(cookie.Value), out cookieTime);
            if (!res || cookieTime < DateTime.Now)
            {
                TempData["error"] = ERROR_SESSION_TIMEOUT;
                return RedirectToAction("Login");
            }
            var editorModel = new EditorModel();
            using (var connection = DataContextFactory.Create())
            {
                var categories =
                    from category in connection.GetTable<Category>()
                    select category;
                foreach (var item in categories)
                {
                    editorModel.AddCategory(item);
                }
            }
            if (TempData["error"] != null)
            {
                ViewData["error"] = System.Web.HttpContext.GetGlobalResourceObject("ErrorMessages",
                                                                                   (String) TempData["error"]);
            }
            if (TempData["ok"] !=null)
            {
                ViewData["ok"] = System.Web.HttpContext.GetGlobalResourceObject("Messages",
                                                                                   (String)TempData["ok"]);
            }
            return View("EditorView", editorModel);
        }



    }
}
